package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author hm
 * @version 1.0
 * @date Created in 2024/7/9 10:58
 */
@Service
public class DishServiceImpl implements DishService {
    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;
    @Resource
    private SetmealDishMapper setmealDishMapper;
    @Resource
    private SetmealMapper setmealMapper;

    @Override
    @Transactional//加上事务控制
    public void save(DishDTO dishDTO) {
        //1.转成dish对象
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //2.设置状态为停售
        dish.setStatus(StatusConstant.DISABLE);
        //3.添加dish到数据表中Dish
        dishMapper.insert(dish);
        //新增菜品id
        Long dishId = dish.getId();
        //4.添加菜品得口味，多条记录
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        //4.1判断是否有口味，有就需要遍历并添加口味表
        if (!CollectionUtils.isEmpty(flavorList)){
            for (DishFlavor flavor : flavorList){
                flavor.setDishId(dishId);
            }
            dishFlavorMapper.insert(flavorList);
        }
        //5.操作2张表，要加上事务处理（事务控制）

    }

    @Override
    public PageResult page(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> page = dishMapper.page(dto);//后绪步骤实现
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * - 可以一次删除一个菜品，也可以批量删除菜品
     * - 起售中的菜品不能删除
     * - 被套餐关联的菜品不能删除
     * - 删除菜品后，关联的口味数据也需要删除掉
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        if (!CollectionUtils.isEmpty(ids)){
            for (Long dishId : ids){
                Dish dish = dishMapper.getById(dishId);
                if(dish.getStatus() == StatusConstant.ENABLE){//起售中的菜品不能删除
                    throw new  DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                }
                List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
                if(!CollectionUtils.isEmpty(setmealIds)){//被套餐关联的菜品不能删除
                    throw new  DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
                }
                for (Long id : ids){//删除菜品后，关联的口味数据也需要删除掉
                    dishMapper.deleteById(id);
                    dishFlavorMapper.deleteById(id);
                }

            }
        }
    }

    /**
     * 根据id查询菜品和口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getById(long id) {
        DishVO dishVO = new DishVO();
        Dish dish = dishMapper.getById(id);
        BeanUtils.copyProperties(dish,dishVO);
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }
    /**
     * 菜品启售、停售
     * @param status
     * @param id
     */
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        // 如果是停售操作，还需要将包含当前菜品的套餐也停售
        if (status.equals(StatusConstant.DISABLE)) {
            // 联表查询setmeal、dish、setmeal_dish
            List<Setmeal> setmealList = setmealMapper.getByDishId(id);
            for (Setmeal setmeal : setmealList) {
                if (setmeal != null) {  //有关联的套餐才需要执行update操作，注意判空处理，否则NPE
                    setmeal.setStatus(StatusConstant.DISABLE);
                    setmealMapper.update(setmeal);
                }
            }
        }
    }
    @Override
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        dishFlavorMapper.deleteById(dishDTO.getId());
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(flavorList)){
            flavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insert(flavorList);
        }

    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
